{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 除法转乘法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "代码实现见 `tvm/src/relay/transforms/div_to_mul.cc`，使用如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tvm\n",
    "from tvm import relay\n",
    "import numpy as np\n",
    "\n",
    "for dtype, rtol in [(\"float16\", 1e-3), (\"float32\", 1e-7), (\"float64\", 1e-12)]:\n",
    "    x = relay.var(\"x\", relay.TensorType((), dtype))\n",
    "    y = relay.Constant(tvm.nd.array(np.array([1.5]).astype(dtype)))\n",
    "    z = x / y\n",
    "    mod = tvm.IRModule.from_expr(z)\n",
    "    transformed = relay.transform.DivToMul()(mod)\n",
    "    assert transformed[\"main\"].body.op.name == \"multiply\"\n",
    "    np.testing.assert_allclose(transformed[\"main\"].body.args[1].data.numpy()[0], 1 / 1.5, rtol=rtol)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "tvmz",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
